#include "OCMain/FileUtil.h"
#include "OCMain/Environment.h"
#include "OCMain/Log.h"
#include "OCServer/AliasManager.h"
#include "OCServer/ServerUtil.h"

using namespace OCPP;

template <typename T>
inline std::vector<T> getYmlVec(const YAML::Node& node)
{
	std::vector<T> vec;
	if (node.Type() == YAML::NodeType::Sequence)
	{
		try {
			for (const auto& c : node)
			{
				vec.push_back(c.as<T>());
			}
		}
		catch (...) {}
	}

	return vec;
}

AliasManager* _aliasManager = NULL;

void init()
{
	_aliasManager = new AliasManager();

	String yamlFileName = Singleton(Environment).getAppPath() + "config/OCPP_ControllerAlias.yml";
	try {
		YAML::Node node = YAML::LoadFile(yamlFileName);
		for (const auto& child : node)
		{
			const auto& map = child.second;
			String alias = getYmlValue<String>(map, "alias", "");
			String path = getYmlValue<String>(map, "path", "");
			bool makeGZ = getYmlValue<bool>(map, "makeGZ", false);
			_aliasManager->setAutoMakeGZ(alias, makeGZ);
			_aliasManager->registerAlias(alias, U2A(path));
		}
	}
	catch (const YAML::Exception& e) {
		LOG_ERROR << e.msg << "\n";
	}
}

void release()
{
	CORE_SAFE_DELETE(_aliasManager);
}